import bpy
from bpy.types import Panel
from ..addon.icons import get_icon
from ..addon.read_addon_version import read_addon_version
from ..addon.naming import FluidLabNaming
# from ..libs.functions.common_ui_elements import collapsable
from ..libs.functions.get_common_vars import get_common_vars
from ..libs.functions.common_ui_elements import collapsable
from ..libs.functions.particles import get_particle_count


def fluid_grous_emitters_list(layout, wm, ui, fluid_groups, active_group):
    lists_row = layout.row(align=True)
            
    # Fluid Groups List:
    left_col = lists_row.column(align=True)
    
    left_title_col = left_col.box().row(align=True)
    left_title_col.alignment = 'CENTER'
    left_title_col.label(text="Fluid Groups")

    # Si abro el popup de fluid interactions oculto el listado:
    if not wm.get(FluidLabNaming.WM_POPUP_OPENED):
        
        # Si no hay popup abierto:
        left_col.template_list("FLUIDLAB_UL_draw_fluids_groups", "", fluid_groups, "list", fluid_groups, "list_index", rows=3)
    
    else:
        fake_group_list = left_col.box()
        fake_group_list.scale_y = 3.5
        fake_group_list.scale_x = 1.1
        fake_group_list.label(text=" ")

    add_grp_bt = left_col.row(align=True)
    add_grp_bt.scale_y = 1.3
    add_grp_bt.operator("fluidlab.fluid_group_list_add")

    add_grp_bt.operator("fluidlab.group_list_item_move", icon='TRIA_UP', text="").direction = 'UP'
    add_grp_bt.operator("fluidlab.group_list_item_move", icon='TRIA_DOWN', text="").direction = 'DOWN'

    dropdown = add_grp_bt.row(align=True)
    dropdown.menu("FLUIDLAB_MT_group_list_submenu", text="", icon='DOWNARROW_HLT')

    # Fluid Emiters List: 
    right_col = lists_row.column(align=True)
    
    if active_group:
        right_col.scale_x = 1.18 if active_group.emitters.is_void else 1 

    
    right_title_col = right_col.box().row(align=True)
    right_title_col.alignment = 'CENTER'

    if active_group:
        right_title_col.label(text=active_group.emitter_type.title() + " Emitters")
    else:
        right_title_col.label(text="Fluid Emitters")

    if active_group:
        fluid_emitters = active_group.emitters

        # Si abro el popup de fluid interactions oculto el listado:
        if not wm.get(FluidLabNaming.WM_POPUP_OPENED):
            
            # Si no hay popup abierto:
            right_col.template_list("FLUIDLAB_UL_draw_fluids_emitters", "", fluid_emitters, "list", fluid_emitters, "list_index", rows=3)
        
        else:
            fake_emitters_list = right_col.box()
            fake_emitters_list.scale_y = 3.5
            fake_emitters_list.scale_x = 1.1
            fake_emitters_list.label(text=" ")
        
        add_emit_bt = right_col.row(align=True)
        add_emit_bt.scale_y = 1.3
        add_emit_bt.operator("fluidlab.fluid_emitters_list_add", text="Add Emitter")
        
        add_emit_bt.operator("fluidlab.emitters_list_item_move", icon='TRIA_UP', text="").direction = 'UP'
        add_emit_bt.operator("fluidlab.emitters_list_item_move", icon='TRIA_DOWN', text="").direction = 'DOWN'

        dropdown = add_emit_bt.row(align=True)
        dropdown.menu("FLUIDLAB_MT_emitters_list_submenu", text="", icon='DOWNARROW_HLT')

    else:
        fake_list = right_col.box()
        fake_list.scale_y = 3.5
        fake_list.scale_x = 1.1
        fake_list.label(text=" ")
        add_fake_bt = right_col.row(align=True)
        add_fake_bt.scale_y = 1.3
        add_fake_bt.enabled = False
        add_fake_bt.prop(ui, "fake_button", text="Create Emitter", toggle=True)


class FLUIDLAB_PT_main_ui(Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_idname = "FLUIDLAB_PT_main"
    bl_label = FluidLabNaming.FluidLab + " %s" % read_addon_version()
    bl_category = FluidLabNaming.FluidLab

    def draw_header(self, context):
        self.layout.label(text="", icon_value=get_icon("FluidLab_Logo_256"))

    def draw(self, context):

        scn, fluid_groups, ui, toggles = get_common_vars(context, get_scn=True, get_fluid_groups=True, get_ui=True, get_toggles=True)
        active_group = fluid_groups.active
        wm = context.window_manager

        layout = self.layout

        # # Con botones Basic/Advanced:
        # button_settings = {
        #     "type": "prop",
        #     "from": ui,
        #     "prop": "ui_mode",
        #     "text": "Presets",
        #     "toggle": True,
        #     "icon": None,
        #     "expand": True
        # }


        # # Con Boton, Scene Presets        
        # button_settings = {
        #     "type": "prop",
        #     "from": toggles,
        #     "prop": "show_hide_presets",
        #     "text": "Scene Preset",
        #     "toggle": True,
        #     "icon": None,
        #     "expand": False
        # }

        layout_lists = collapsable(
            layout,
            toggles,
            "fluids_list",
            "Fluids List",
            'MOD_FLUIDSIM',
            align=True,
            # Sin botones comento button_settings1:
            #button_settings1=button_settings,
        )
        if layout_lists:
            # if not toggles.show_hide_presets:    
            # Listados de Fluid Groups y Fluids Emitters:
            fluid_grous_emitters_list(layout_lists, wm, ui, fluid_groups, active_group)
                
        

        # MAIN MODULES ----------------------------------------------------------------------------------
        sections = layout.column(align=True)
        box = sections.box().row()
        box.scale_y = 0.8

        header_1 = box.row(align=True)
        header_1.emboss = 'PULLDOWN_MENU'
        header_1.alignment = 'LEFT'

        if ui.collapse_module_selector:

            # renaming on the fly: Activators to Activators
            main_modules = ui.main_modules
            if main_modules == 'ACTIVATORS':
                main_modules = "Activators"

            header_1.prop(ui, "collapse_module_selector", text="Main Modules [ %s ]" % (main_modules.capitalize()), icon='WINDOW', emboss=False)

        else:
            header_1.prop(ui, "collapse_module_selector", text="Main Modules", icon='WINDOW', emboss=False)

        header_2 = box.row(align=True)
        header_2.emboss = 'PULLDOWN_MENU'
        header_2.alignment = 'RIGHT'
        header_2.prop(ui, "collapse_module_selector", text="", icon='ADD' if ui.collapse_module_selector else 'REMOVE', emboss=False)

        if ui.collapse_module_selector:
            size_items = len(ui.module_items)
            sections = sections.grid_flow(
                row_major=True, even_columns=True,
                even_rows=True, align=True, columns=size_items
            )
            sections.scale_y = 1.3
            sections.prop(ui, "main_modules_collapsed", text="",  expand=True)
        else:
            sections = sections.grid_flow(
                row_major=True, even_columns=True,
                even_rows=True, align=True, columns=2
            )
            sections.scale_y = 1.3
            sections.prop(ui, "main_modules", expand=True)
                
        # END MAIN MODULES ------------------------------------------------------------------------------
        
        section_down = layout.column(align=True)

        # Bake section
        enable_bake = False
        all_groups = fluid_groups.get_all_items
        enable_bake = next((True for group in all_groups if not group.emitters.is_void), False)

        bake_grid = section_down.box().grid_flow(row_major=True, even_columns=True, even_rows=False, align=True, columns=2)
        bake_grid.enabled = enable_bake

        col1 = bake_grid.row(align=True)
        col1.scale_y = 1.3
        col1.operator("fluidlab.bake_current_cache", text="Current Cache", icon='PLAY')
        
        # Dejamos comentados los operadores y la ui y el SS_SRT_STP, porque al final parece que no lo vamos a usar:
        # if context.screen.is_animation_playing and FluidLabNaming.SS_SRT_STP in wm:
        #     col1.operator("fluidlab.bake_stop_simulation", text="Stop Simulation", icon='SNAP_FACE')
        # else:
        #     col1.operator("fluidlab.bake_start_simulation", text="Start Simulation", icon='PLAY')

        dpress = scn.fluidlab["current_cache_baked"] if "current_cache_baked" in scn.fluidlab else False
        col1.operator("fluidlab.current_cache_to_bake", text="", icon='DISK_DRIVE', depress=dpress)
        
        col2 = bake_grid.row(align=True)
        col2.scale_x = 1.1
        col2.scale_y = 1.3
        
        # col2.operator("ptcache.bake_all", text="Bake All") # <- el de blender
        col2.operator("fluidlab.bake_all", text="Bake All") # <- el nuestro, primero hacemos un refresh cache
        # col2.operator("fluidlab.bake_current_cache", text="Current Cache")

        col2.operator("fluidlab.bake_refresh_cache", text="", icon='FILE_REFRESH')
        trash_bt = col2.row(align=True)
        trash_bt.alert = True

        # trash_bt.operator("ptcache.free_bake_all", text="", icon='TRASH')
        trash_bt.operator("fluidlab.bake_ptcache_free_bake_all", text="", icon='TRASH')
        
        # End Bake section

        size_y = 0.45
        # Feedback particle info:
        if all_groups:

            # Obtengo todos los emisores de todos los grupos para contar el total de particulas de todos los grupos:                            
            all_emitters = [group.emitters.get_all_emitters for group in all_groups]
            
            # Aplanando en una sola lista todos los emittes:
            all_emitters = [objeto for sublista in all_emitters for objeto in sublista]

            if len(all_emitters) <= 0:
                return

            section_down.separator(factor=0.2)
            
            count_info = (get_particle_count(context, emitter) for emitter in all_emitters)

            flow = section_down.grid_flow(row_major=True, even_columns=True, even_rows=False, align=True, columns=2)
            flow.scale_y = size_y
            spaces = "    "

            hd_1 = flow.box().row(align=True)
            hd_1.alignment = 'LEFT'
            hd_1.label(text=f" Total Particles:" + "   ")
            
            count_1 = hd_1.row(align=True)
            count_1.alignment = 'LEFT'
            count_1.label(text=spaces + str(sum(count_info)))

            emitters_list = active_group.emitters
            if emitters_list.length > 0:
                emitter_ob = emitters_list.get_current_emitter
                
                if emitter_ob:

                    hd_2 = flow.box().row(align=True)
                    hd_2.alignment = 'LEFT'
                    # hd_2.label(text=f"{emitter_ob.name.title()} Particles: " + spaces)
                    hd_2.label(text=f"Particles: " + spaces)

                    count_2 = hd_2.row(align=True)
                    count_2.alignment = 'LEFT'
                    count_2.label(text=spaces + str(get_particle_count(context, emitter_ob)))

                # size cuando es de tipo grid:
                # if active_group.emitter_type == 'GEOMETRY':
                section_down.separator(factor=1.2)
                flow = section_down.grid_flow(row_major=True, even_columns=True, even_rows=False, align=True, columns=2)
                flow.scale_y = size_y

                hd_3 = flow.box().row(align=True)
                text_last_bake = "  Last Bake: " + context.scene.fluidlab.last_bake_time if len(context.scene.fluidlab.last_bake_time) >0 else ""
                hd_3.label(text=text_last_bake)

                hd_4 = flow.box().row(align=True)
                hd_4.alignment = 'LEFT'
                # hd_4.label(text=f"{emitter_ob.name.title()} Particle Size:")
                hd_4.label(text=f"Part Size:")

                if emitter_ob:
                    psys = emitter_ob.particle_systems.active
                    if psys:
                        # valdría particle_size o display_size
                        value_size = "{:.3f}".format(psys.settings.display_size).rstrip('0').rstrip('.')

                        count_4 = hd_4.row(align=True)
                        count_4.alignment = 'LEFT'
                        count_4.label(text="         " + str(value_size) + "m")
            else:
                hd_3 = flow.box().row(align=True)
                hd_3.label(text=" ")
                hd_3.label(text=" ")
